package com.power.project.dao;

import com.power.project.model.Ww_depart;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.lang.Nullable;

import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.List;

/**
 * 企业微信部门信息 持久层(hibernate)
 */

public interface Ww_departDao extends JpaRepository<Ww_depart, Serializable>, JpaSpecificationExecutor<Ww_depart>, Repository<Ww_depart, Serializable>, Ww_departDaoCustom<Ww_depart, Serializable> {


    List<Ww_depart> findByTenantidEquals(@Nullable String tenantid);

    /**
     * 根据父级id和租户id查询部门列表，按照sortnum倒序排列
     *
     * @param parentid
     * @param tenantid
     * @return
     */
    @Query("select w from Ww_depart w where w.parentid = ?1 and w.tenantid = ?2 order by w.sort_num DESC")
    List<Ww_depart> findByParentidAndTenantid(String parentid, String tenantid);


    @Query("select wd from Ww_depart wd left join Ww_depart_user w on w.departid = wd.departid and w.tenantid = :tenantId and w.isleader = 1 and w.wwuserid = :userId " +
            "where wd.tenantid = :tenantId and w.id is not null")
    List<Ww_depart> getLeadDepartment(String userId, String tenantId);

    @Modifying
    @Transactional
    @Query(value = "UPDATE ww_depart wd " +
            "LEFT JOIN (SELECT departid,group_concat(wwuserid) AS userids FROM ww_depart_user WHERE tenantid=:tenantId AND isleader=1 GROUP BY departid) tmp " +
            "ON tmp.departid=wd.departid SET wd.department_leader=tmp.userids " +
            "WHERE wd.tenantid=:tenantId AND wd.departid IN (:departIds)", nativeQuery = true)
    void resetLeaders(List<String> departIds, String tenantId);

    @org.springframework.transaction.annotation.Transactional
    @Modifying
    @Query("delete from Ww_depart w where w.departid = ?1")
    int deleteByDepartId(String departId);

    @Query("select w from Ww_depart w where w.departid = ?1")
    Ww_depart getByDepartId(String departId);

    @Query("select w from Ww_depart w where w.departid in ?1")
    List<Ww_depart> findAllByDepartId(List<String> departIds);

    @Query("select w from Ww_depart w where w.tenantid = ?1")
    List<Ww_depart> queryAllDepartWechat(String tenantId);

    @Query("select w from Ww_depart w where w.parentid = ?1")
    List<Ww_depart> getByParentId(String parentId);

    @Modifying
    @Transactional
    @Query("update Ww_depart w set w.department_leader = ?2 where  w.departid = ?1 ")
    void updateleaderById(String departId,String leaderIdsBO);
}
